package angry.courses.servlets;

import java.io.PrintWriter;

import java.util.List;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import javax.servlet.ServletException;

import angry.courses.entities.CourseEntity;

public class RemoveCourseServlet extends HttpServlet {
    
    public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html");

		CourseDelegate courseDelegate = new CourseDelegate();
		final List<String> courseNames = new ArrayList<String>();
		courseNames.addAll(courseDelegate.getCourseNamesForSemester(1));
		courseNames.addAll(courseDelegate.getCourseNamesForSemester(2));

		PrintWriter out = res.getWriter();
		out.println(new HtmlFormatter() {

			public String title() {
				return "Remove Course";
			}

			public void body(StringBuffer buf) {
				if (courseNames.size() > 0) {
					form(buf);
				} else {
					buf.append("No courses exist at the moment.<br>");
					buf.append("Click " + link("here", "admin.html") +
						" to go back.");
				}
			}

			public void form(StringBuffer buf) {
				buf.append(heading(3, "Select the course: "));
				buf.append("<form method=\"post\" action=\"RemoveCourse\" >");
				buf.append(dropdown("course", "", courseNames));
				buf.append(" " +  button("Delete"));
				buf.append("</form>");
			}
        }.htmlTag());
		out.close();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		final String courseName = req.getParameter("course");
	
		CourseDelegate courseDelegate = new CourseDelegate();
		final CourseEntity course = courseDelegate.getCourse(courseName);
		RegisterDelegate registerDelegate = new RegisterDelegate();
		registerDelegate.deleteRelationsForCourse(course);
		courseDelegate.removeCourse(course);

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println(new HtmlFormatter() {
			public String title() {
				return "Course removed";
			}

			public void body(StringBuffer buf) {
				buf.append(heading(3, "Completed"));
				buf.append("Removed course \"" + course.getName() + "\".<br>");
				buf.append("Click " + link("here", "admin.html") +
					" to go back.");
			}
		}.htmlTag());
		out.close();
    }
}
